package com.oocl.customersystem.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class RequestUtil {

	public static final String POST = "POST";
	public static final String GET = "GET";
	
	@SuppressWarnings("rawtypes")
	public static Object request(String uri, String type,String params, Class clazz)throws IOException{
		Object obj = null;
		try {
			URL url = new URL(uri);
			URLConnection conn = url.openConnection();
			HttpURLConnection httpconn = (HttpURLConnection) conn;
			if(POST.equals(type)){
				httpconn.setRequestMethod("POST");
				if(null!=params){
					System.out.println(params+"****************");
					httpconn.setDoOutput(true);
					OutputStream out = httpconn.getOutputStream();
					PrintWriter writer = new PrintWriter(out,true);
					writer.println(params);
					writer.println("\n");					
				}
				InputStream in = httpconn.getInputStream();
				BufferedReader reader = new BufferedReader(new InputStreamReader(in));
				String jso=reader.readLine();
							
				System.out.println(jso+"-++++++++++++++++++++");
				in.close();
				reader.close();
				httpconn.disconnect();
				return jsonToObj(jso, clazz);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ProtocolException e) {
			e.printStackTrace();
		} 
		return obj;
	}
	
	public static String wrapToJson(Object obj){
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return null;  
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Object jsonToObj(String json, Class clazz) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.readValue(json, clazz);
			
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

}
